package com.soil.code.generation.database.factory;

import java.sql.SQLException;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zeno
 */
public class DatabaseInfoRepositoryFactoryManager{

  private static final ConcurrentHashMap<String,Class<? extends DatabaseInfoRepositoryFactory>> REGISTERED;

  static{

    REGISTERED = new ConcurrentHashMap<>();

    // 编辑注册进来的数据库信息仓储类，将仓库类注册
    for(DatabaseInfoRepositoryFactory factory : ServiceLoader.load(DatabaseInfoRepositoryFactory.class)){
      DatabaseInfoRepositoryFactoryManager.register(factory.type(), factory.getClass());
    }
  }

  public static void register(
    String dbType,Class<? extends DatabaseInfoRepositoryFactory> factoryClass ){

    if( REGISTERED.containsKey(dbType) ){
      throw new IllegalArgumentException("数据库类型 " + dbType + " 已经被注册");
    }

    REGISTERED.put(dbType,factoryClass);
  }

  public static void unregister( String dbType ){
    REGISTERED.remove(dbType);
  }

  public static DatabaseInfoRepositoryFactory doGet(
    String dbType ) throws SQLException, InstantiationException, IllegalAccessException{
    Class<? extends DatabaseInfoRepositoryFactory> aClass = REGISTERED.get(dbType);

    if( aClass == null ){
      throw new IllegalArgumentException("未发现数据库支持类型:" + dbType);
    }

    return aClass.newInstance();
  }
}
